<!--
 * @Author: your name
 * @Date: 2022-03-28 08:36:12
 * @LastEditTime: 2024-04-25 16:38:54
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \trace-source-web\src\views\trace-source-manage\components\print\print.vue
-->
<template>
  <div v-loading="loading" class="dashboard-container">
    <el-button type="button" class="xunzeimage" @click="onPickFile">点击上传 Excel</el-button>
    <input
      ref="upload"
      type="file"
      accept=".xls, .xlsx"
      class="outputlist_upload"
      style="display: none"
    />
    <br />
    <el-form ref="form" :model="form">
      <el-form-item label="跳转链接：">
        <el-input v-model="url" clearable />
      </el-form-item>
      <el-form-item label="参数编号：">
        <el-input v-model="titleNos" clearable placeholder="编号" />
      </el-form-item>
      <el-form-item label="参数名称：">
        <el-input v-model="titleNames" clearable placeholder="名称" />
      </el-form-item>
      <el-form-item label="参数编号字段：" class="w50p">
        <el-select
          v-model="titleNo"
          allow-create
          :placeholder="outputs.length !== 0 ? '请选择' : '请先上传Excel'"
        >
          <el-option
            v-for="item,index in outputs"
            :key="index"
            :value="item.id"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="参数名称字段：" class="w50p">
        <el-select
          v-model="titleName"
          allow-create
          :placeholder="outputs.length !== 0 ? '请选择' : '请先上传Excel'"
        >
          <el-option
            v-for="item,index in outputs"
            :key="index"
            :value="item.id"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <el-button size="small" type="info" @click="titleListTo">生成</el-button>
    <el-button size="small" type="info" @click="downLoadQr">单个二维码图片</el-button>
    <el-button size="small" type="info" @click="batchDownload">批量二维码图片</el-button>
    <el-button size="small" type="info" @click="print">批量打印</el-button>
    <!-- <el-table :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="id" width="180" />
      <el-table-column label="图片" width="180">
        <template slot-scope="scope">
          <img :src="scope.row.src" class="table_img" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="print(scope.row)">打印</el-button>
        </template>
      </el-table-column>
    </el-table>-->
    <!--startprint-->
    <div id="printcontent" ref="printcontent">
      <div v-for="item in tableData" :key="item.id" class="print_img">
        <h2>{{ item.name }}</h2>
        <p>
          <vue-qr
            class="vue-qr"
            :text="item.url"
            :margin="10"
            color-dark="#000"
            color-light="#fff"
            :dot-scale="1"
            :logo-scale="0.2"
            :size="300"
            :logo-src="item.icon"
          />
        </p>
      </div>
      <!-- <img v-for="item in tableData" :key="item.id" :src="item.src" class="print_img" /> -->
    </div>
    <div
      v-for="(item, index) in checkedList"
      ref="qrBox"
      :key="index"
      style="text-align: center; width: 180px;display: flex ; justify-content: center;align-items: center;"
    >
      <!-- 二维码挂在的DOM -->
      <canvas ref="codeItem"></canvas>
      <!-- 二维码下面的描述
      <div>{{ item.name }}</div>-->
    </div>

    <div
      ref="creditQrCodeShare"
      class="box"
      style="text-align: center; width: 210px;display: flex ; justify-content: center;align-items: center; padding: 5px;background: #fff;margin-top: 10px;"
    >
      <div
        id="qrCode"
        class="qr_code mt-15 flex-row justify-center"
        style="text-align: center; width: 200px;display: flex ; justify-content: center;align-items: center;"
      >
        <!-- <img :src="merchantMsg.qrCode" alt="" /> -->
      </div>
    </div>
    <!--endprint-->
  </div>
</template>

<script>
import vueQr from "vue-qr";
import { read, utils } from "xlsx";
import QRCode from "qrcode";
import QRCode2 from "qrcodejs2";
import JSZip from "jszip";
import FileSaver from "file-saver";
import html2canvas from "html2canvas";
export default {
  components: { vueQr },
  props: {
    // tableData: {
    //   type: Array,
    //   default: () => []
    // }
  },
  data() {
    return {
      multipleSelection: [], // 存放将要打印的数据
      tableData: [],
      outputs: [],
      url: `${this.$serviceUrl}/mateFarmTraceSource/#/pages/facility-message/facility-message?facilityNo=`,
      titleNo: "",
      titleName: "",
      titleNos: "",
      titleNames: "",
      printcontentData: [],
      checkedList: [],
      form: {},
      loading: false
    };
  },
  mounted() {
    this.$refs.upload.addEventListener("change", (e) => {
      // 绑定监听表格导入事件
      this.readExcel(e);
    });
  },
  methods: {
    onPickFile() {
      this.$refs.upload.click();
    },
    print(row = {}) {
      // if (row.src) {
      //   this.multipleSelection.push(row);
      // }
      this.$nextTick(() => {
        var bdhtml = window.document.body.innerHTML; // 获取body的内容
        var jubuData = document.getElementById("printcontent").innerHTML; // 获取要打印的区域内容
        window.document.body.innerHTML = jubuData;
        window.print(); // 调用浏览器的打印功能
        window.document.body.innerHTML = bdhtml; // body替换为原来的内容
        window.location.reload(); // 刷新页面，如果不刷新页面再次点击不生效或打印使用新窗口实现打印
      });
    },
    titleListTo(e) {
      if (this.titleNo && this.titleName && this.url) {
        let EMPTY_4 = [];
        this.printcontentData.forEach((item, index) => {
          if (item[this.titleNo] && index !== 0) {
            // console.log(item);
            EMPTY_4.push({
              url: this.url + item[this.titleNo],
              name: item[this.titleName],
              no: item[this.titleNo]
            });
          }
        });
        console.log(EMPTY_4);
        this.tableData = EMPTY_4;
      } else {
        this.$message.warning("请选择完整参数");
      }
    },
    readExcel(e) {
      // var that = this;
      this.printcontentData = [];
      const files = e.target.files;
      // 如果没有文件名
      if (files.length <= 0) {
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }

      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          // 切换为新的调用方式
          const workbook = read(data, {
            type: "binary"
          });
          // 取第一张表
          const wsname = workbook.SheetNames[0];
          console.log(wsname, workbook);

          // 切换为新的调用方式 生成json表格内容
          const ws = utils.sheet_to_json(workbook.Sheets[wsname]);
          console.log(ws);
          this.printcontentData = [...ws];
          // let arr = Object.values(ws[0]);
          let key = Object.keys(ws[0]); // 取出当前对象的索引

          let values = Object.values(ws[0]); // 取出当前对象的值
          let arrObj = key.map((item, index) => {
            return {
              name: values[index], // values是一个数组，加index是为了拿到跟索引同个位置的值
              id: item
            };
          });
          this.outputs = arrObj.splice(1);
          console.log(this.outputs);
          // let EMPTY_4 = [];
          // ws.forEach((item, index) => {
          //   if (item.__EMPTY_4 && index !== 0) {
          //     // console.log(item);
          //     EMPTY_4.push({
          //       url: item.__EMPTY_4,
          //       name: item.__EMPTY_5
          //     });
          //   }
          // });
          // console.log(EMPTY_4);

          // 后续为自己对ws数据的处理
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
    downLoadQr(row) {
      this.checkedList = [
        {
          url: this.url + this.titleNos,
          name: this.titleNames
        }
      ];
      this.$nextTick(() => {
        QRCode.toCanvas(
          this.$refs.codeItem[0],
          this.checkedList[0].url,
          {
            height: 180,
            width: 180,
            margin: 1
          },
          (error) => {
            if (error) console.log(error);
            html2canvas(this.$refs.qrBox[0]).then((canvas) => {
              let dataURL = canvas.toDataURL("image/png");
              console.log(dataURL);
              if (dataURL !== "") {
                var a = document.createElement("a");
                a.download = this.checkedList[0].name;
                a.href = dataURL;
                a.click();
              }
            });
          }
        );
      });
    },
    // 生成二维码
    QrcodeInit(row) {
      this.qrcode = new QRCode2(document.getElementById("qrCode"), {
        text: row.url,
        width: 200,
        height: 200,
        colorDark: "#333333", // 二维码颜色
        colorLight: "#ffffff", // 二维码背景色
        correctLevel: QRCode2.CorrectLevel.L // 容错率，L/M/H
      });
    },
    // 删除二维码
    removeCode() {
      const codeHtml = document.getElementById("qrCode");
      while (codeHtml.firstChild) {
        codeHtml.removeChild(codeHtml.firstChild);
      }
    },
    // // 批量下载图片  list为需要生成得所有数据 （会导致崩溃）
    // downloadImage() {
    //   this.checkedList = [];
    //   this.checkedList = [...this.tableData];
    //   let list = [];
    //   let indexs = parseInt(this.tableData.length / 50);
    //   // console.log(indexs);

    //   for (let i = 1; i < indexs + 1; i++) {
    //     // if (this.tableData.length > 50) {
    //     if (i === 1) {
    //       list.push(this.tableData.slice(0, 50 * i));
    //     } else {
    //       list.push(this.tableData.slice(50 * (i - 1), 50 * i));
    //     }
    //     // }
    //   }
    //   // console.log(list);
    //   // return;
    //   // console.log(list);
    //   // console.log(list);

    //   this.$nextTick(() => {
    //     list.forEach(async (ie) => {
    //       // const base64Array = [];
    //       await ie.forEach(async (item, index) => {
    //         let doc = this.$refs.codeItem[index];
    //         // let
    //         await QRCode.toCanvas(
    //           doc,
    //           item.url,
    //           {
    //             height: 180,
    //             width: 180,
    //             margin: 1
    //           },
    //           async (error) => {
    //             // console.log(1);
    //             if (error) console.log(error);
    //             html2canvas(this.$refs.qrBox[0]).then((canvas) => {
    //               let dataURL = canvas.toDataURL("image/png");
    //               console.log(dataURL);
    //               if (dataURL !== "") {
    //                 var a = document.createElement("a");
    //                 a.download = this.checkedList[0].name;
    //                 a.href = dataURL;
    //                 a.click();
    //               }
    //               // base64Array.push({
    //               //   name: item.name,
    //               //   data: canvas
    //               //     .toDataURL()
    //               //     .replace(/^data:image\/(png|jpg);base64,/, "")
    //               // });
    //               // console.log(base64Array.length, ie.length);
    //               // if (base64Array.length === ie.length) {
    //               //   await this.downloadZip(base64Array);
    //               // }
    //             });
    //           }
    //         );
    //       });
    //     });
    //   });
    // },

    // 图片生成下载
    async batchDownload() {
      this.loading = true;
      this.$message({
        showClose: true,
        message: "打包中",
        type: "success",
        duration: 0
      });
      this.checkedList = [];
      this.checkedList = [...this.tableData];
      if (!this.checkedList.length) {
        return this.$message.warning("暂无生成图片数据");
      }
      const imgList = [];
      const zip = new JSZip();
      let index = 0;
      // 生成图片 根据数据列表生成对应的图片
      for (let i = 0; i < this.checkedList.length; i++) {
        await this.QrcodeInit(this.checkedList[i]); // 二维码绘制
        // await this.handleVal(this.checkedList[i]); // 赋值 页面上显示不同的数据，每次遍历进行赋值

        await html2canvas(this.$refs.creditQrCodeShare, {
          backgroundColor: null, // 画出来的图片有白色的边框,不要可设置背景为透明色（null）
          useCORS: true, // 支持图片跨域
          scale: 1 // 设置放大的倍数
        }).then((canvas) => {
          this.removeCode(); // 每次循环生成都要把之前的数据删掉
          let url = canvas.toDataURL("image/png"); // toDataURL: 图片格式转成 base64
          imgList.push({
            url,
            name: this.checkedList[i].no + "-" + this.checkedList[i].name
          });
          // 压缩转码
          if (imgList.length === this.checkedList.length) {
            for (let i = 0; i < imgList.length; i++) {
              index++;
              let blob = this.dataURLtoBlob(imgList[i].url); // 压缩需要二进制数据把base64转成二进制
              zip.file(imgList[i].name + ".png", blob, { blob: true });
            }
            if (index === imgList.length) {
              zip.generateAsync({ type: "blob" }).then(
                (blob) => {
                  FileSaver.saveAs(blob, "批量下载.zip");
                  this.$message.closeAll();
                  setTimeout(() => {
                    this.$message({
                      showClose: true,
                      message: "打包成功",
                      type: "success",
                      duration: 2000
                    });
                  }, 100);
                  this.loading = false;
                },
                (_err) => {
                  this.$message.error("图片生成失败");
                  this.$message({
                    showClose: true,
                    message: "打包失败",
                    type: "error",
                    duration: 2000
                  });
                  this.$message.closeAll();
                  this.loading = false;
                  // alert("导出失败");
                }
              );
            }
          }
        });
      }
    }, // base64 转 二进制流(blob)
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime
      });
    },
    // 二进制流 转 base64
    getBase64(data) {
      return new Promise((resolve, reject) => {
        const blob = new Blob([data], { type: "image/jpg" }); // 类型一定要写！！！
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
      });
    },
    downloadZip(arr) {
      // 定义压缩包名
      const zipName = `定义压缩包名`;
      const zip = new JSZip();
      arr.forEach((item) => {
        zip.file(item.name, item.data, { base64: true });
      });
      zip.generateAsync({ type: "blob" }).then((content) => {
        FileSaver.saveAs(content, `${zipName}.zip`);
      });
    }
    // allPrint() {
    //   this.print();
    // }
    // handleSelectionChange(val) {
    //   this.multipleSelection = val;
    // }
  }
};
</script>

<style lang="scss" scoped>
::v-deep {
  .el-form {
    margin-top: 20px;
    .el-form-item {
      display: flex;
      width: 100%;
      .el-form-item__label {
        min-width: 120px;
      }
      .el-form-item__content {
        width: 100%;
      }
    }
  }
}
.dashboard-container {
  // .table_img {
  //   width: 50px;
  //   height: 50px;
  // }
  #printcontent {
    display: none;
  }
}
//使用媒体查询    设置预览时的样式
@media print {
  @page {
    margin: 0 auto;
    size: landscape; //设置打印布局portrait为纵向；landscape为横向
  }
  #printcontent {
    width: 100%;
    // text-align: center;
  }
  .print_img {
    display: block;
    width: 100%;
    height: 100%;
    border: 1px solid transparent;
    h2 {
      height: 10%;
      text-align: center;
      // font-size: ;
    }
    p:last-child {
      height: 70%;
      text-align: center;
      img {
        height: 100%;
      }
    }
    // img {
    //   height: calc(100%);
    // }
  }
}
</style>
